package cn.calm.xhtml.util;

import java.util.ArrayList;
import java.util.List;

import cn.calm.xhtml.api.service.XhtmlContext;

public class ValueUtil {
	public static String getValue(String valueStr, XhtmlContext context) {
		List<String> splite = splite(valueStr);
		StringBuilder str = new StringBuilder();
		for (String s : splite) {
			if (s.startsWith("${") && s.endsWith("}")) {
				Object value = context.getValue(s);
				if (value != null) {
					str.append(value);
				}

			} else {
				str.append(s);
			}
		}
		return str.toString();
	}

	// public static Object getExpressValue(OgnlContext context, String express)
	// throws ExpressionSyntaxException {
	// Node compileExpression;
	// try {
	// compileExpression = Ognl.compileExpression(context, context,
	// express);
	// return compileExpression.getValue(context, context);
	// } catch (NoSuchPropertyException e) {
	// return null;
	// } catch (CannotCompileException e) {
	// return null;
	// } catch (ExpressionSyntaxException e) {
	// throw e;
	// } catch (Exception e) {
	// return express;
	// }
	//
	// }
	@Deprecated
	public static Object getExpressValue(XhtmlContext context, String express) {
//		ExpressionFactory factory = context.getFactory();
//		SimpleContext expressContext = context.getExpressContext();
//		ValueExpression vExpression = factory.createValueExpression(expressContext, express, Object.class);
//		try {
//			 vExpression.getValue(expressContext);
			 return context.getValue(express);
//		} catch (PropertyNotFoundException e) {
//			VariableMapper variableMapper = expressContext.getVariableMapper();
//			ValueExpression resolveVariable = variableMapper.resolveVariable(express);
//			try {
//				return resolveVariable.getValue(expressContext);
//			} catch (PropertyNotFoundException e1) {
//				return null;
//			}
//		}
	}

	public static List<String> splite(String value) {
		List<String> result = new ArrayList<String>();
		int indexOf = value.indexOf("${");
		if (indexOf >= 0) {
			result.add(value.substring(0, indexOf));
			int substring = value.indexOf("}", indexOf);
			if (substring > 0) {
				result.add(value.substring(indexOf, substring + 1));
				String substring2 = value.substring(substring + 1);
				result.addAll(splite(substring2));
			} else {
				result.add(value);
			}
		} else {
			result.add(value);
		}
		return result;
	}
}
